package org.icrisat.mbdt.ui.dialog;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.ide.IDE;
import org.icrisat.mbdt.database.DBConnection;
import org.icrisat.mbdt.database.DBOperations;
import org.icrisat.mbdt.model.RootModel;
import org.icrisat.mbdt.model.TargetGenotype.TargetGeno;

/**
 * SwapnaNair December 2009
 **/
public class CustomAction extends Action implements IWorkbenchAction {
	
	Connection con = null;
	Statement stmt = null;ResultSet rs = null;	
	Statement stmt1 = null;ResultSet rs1 = null;	
	Statement stmtGene = null;ResultSet rsGene = null;	
	Statement stmtAcc = null;ResultSet rsAcc = null;
	Statement stmtAcc1 = null;ResultSet rsAcc1 = null;
	Statement stmtMar = null;ResultSet rsMar = null;
	Statement stmtMar1 = null;ResultSet rsMar1 = null;
	Statement stmtAllele = null;ResultSet rsAllele = null;
	ResultSet rs2 = null;
	int projectId = 0; int generationId = 0;
	int accessionId = 0; int markerId = 0; int alleleId = 0; int intAlleleVal = 0;
	String message = "";
	String values = ""; String queryValues = "";
	String accValues = ""; String markerValues = "";
	String alleleValues = "";
	String FlagAlleleType = "";
	int chkForAllele = 1;
	String tablename = "";
	String markerName = "";

	PreparedStatement pst = null;
	PreparedStatement pst1 = null;
	PreparedStatement pst2 = null;
	PreparedStatement pst3 = null;
	PreparedStatement pstQTL = null;
	PreparedStatement pstMk = null;
	PreparedStatement pstSelAcc = null;
	PreparedStatement pstTargetallele = null;
	Statement stmtSelacc = null;ResultSet rsSelacc = null;
	Statement stmtType = null;ResultSet rsType = null;
	Statement stmtTargetAcc = null;ResultSet rsTargetAcc = null;
	Statement stmtTargetMarker = null;ResultSet rsTargetMarker = null;
	Statement stmtTargetAllele = null;ResultSet rsTargetAllele = null;
	Statement stmtTargetType = null;ResultSet rsTargetType = null;
	Statement stmtTargetAlleleFrmDb = null;ResultSet rsTargetAlleleFrmDb = null;
	Statement stmtSaveType = null;
	
	int cnt = 0;int cnt1 = 0; int cnt2 = 0;
	int prevAlleleId = 0; int prevAccId = 0; int prevMarkerId = 0;
	String accInfo = ""; String markerInfo = "";
	ArrayList<Integer> accList = new ArrayList<Integer>();
	ArrayList<Integer> markerList = new ArrayList<Integer>();
	HashMap<Integer, String> markerHMap = new HashMap<Integer, String>();
	HashMap<String, Integer> markerHMapFrmModel = new HashMap<String, Integer>();
	String prevMarkerName = "";
	int maxAlleleId = 0;
	int alleleIdCal = 0;
	int prevAlleleIdCal = 0;
	int targetAccId = 0;
	int targetMarkerId = 0;
	int targetAlleleId = 0;
	int targetTypeId = 0;
	int donorAccId = 0;
	String targetInfo = "";
	String saveType = "";
	String saveTypeToDB = "";
	int ploidy = 0;
	
	/* This class needs a private static final String property 
	 * used to set the ID in the constructor.
	 * 
	 */
	
	//private static final String ID = "com.timmolter.helloWorld.CustomAction";
	private static final String ID = "ISMAB CustomAction";
	
	public CustomAction(){  
	 setId(ID);  
	} 
	
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
		//String dialogBoxTitle = "Message";
		//String message = "You clicked the custom action from the menu!";
		//MessageDialog.openInformation(shell, dialogBoxTitle, message);
		
		//Creating our own Dialog Box.....
		final IsmabSaveAsDialog saveAsdialog = new IsmabSaveAsDialog(shell);
		if(saveAsdialog.open()== Window.OK){
			
			//DataBase Connections.....
			final DBConnection dbConnection = new DBConnection();
			final DBOperations dbOperations = new DBOperations();
					
			

			WorkspaceJob wJob = new WorkspaceJob(targetInfo){
			
				@Override
				public IStatus runInWorkspace(IProgressMonitor monitor)
						throws CoreException {
					//telling the job that we have 2 jobs to perform one loading and two refreshing the view
					monitor.beginTask("Database Operations is in progress", 2);
					//Waiting...i.e we tell the thread to wait for 5 
					try{
						Thread.sleep(5000);
					}catch(InterruptedException e){
						e.printStackTrace();					
					}
					//telling that first job is completed...
					monitor.worked(1);
					monitor.setTaskName("Please wait for a while");
					//Refreshing...
					Runnable run = new Runnable(){
						public void run() {
			//System.out.println(linkData.getMarkallelic()+":::"+linkData.getAccallellic()+"::::"+linkData.getAccWithLabels());
			try {
				
				con = dbConnection.connection();
				stmt = con.createStatement();
				stmt1 = con.createStatement();
				stmtGene = con.createStatement();
				stmtAcc = con.createStatement();
				stmtAcc1 = con.createStatement();
				stmtMar = con.createStatement();
				stmtMar1 = con.createStatement();
				stmtAllele = con.createStatement();
				stmtSelacc = con.createStatement();
				stmtType = con.createStatement();
				stmtTargetAcc = con.createStatement();
				stmtTargetMarker = con.createStatement();
				stmtTargetAllele = con.createStatement();
				stmtTargetType = con.createStatement();
				stmtTargetAlleleFrmDb = con.createStatement();
				stmtSaveType = con.createStatement();
				
				
				pst = con.prepareStatement("INSERT INTO allele_integervalues VALUES(?,?)");
				pst1 = con.prepareStatement("INSERT INTO accessions VALUES(?,?)");
				pst2 = con.prepareStatement("INSERT INTO markers VALUES(?,?)");
				pst3 = con.prepareStatement("INSERT INTO reference VALUES(?,?,?,?)");
				pstQTL = con.prepareStatement("INSERT INTO qtl_details VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
				pstMk = con.prepareStatement("INSERT INTO map_details VALUES(?, ?, ?, ?, ?, ?)");
				pstSelAcc = con.prepareStatement("INSERT INTO selected_accessions VALUES(?, ?, ?)");
				pstTargetallele = con.prepareStatement("INSERT INTO target_genotype VALUES(?, ?, ?, ?, ?, ?, ?)");
				
				
					
				RootModel rootModel = RootModel.getRootModel();
				String projectName = saveAsdialog.getTextData();
				String generationName = saveAsdialog.getText1Data();				
				
				Date date = new Date();
				java.text.SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				String dateOfCreation = dateFormat.format(date);
				
				//For Project....
				rs1 = stmt1.executeQuery("select * from project_details where project_name = '"+projectName+"'");
				if(rs1.next()){
					
					message = "Project name already exists!";
					MessageDialog.openWarning(shell, "Alert", message);
					
				}else{
					rs = stmt.executeQuery("select max(project_id) from project_details");
					while(rs.next()){					
						if(rs.getInt(1) == 0){
							projectId = 1;
						}else{
							projectId = rs.getInt(1) + 1;
						}						
					}			
					
					values = projectId+",'"+ projectName +"','"+ dateOfCreation +"','"+ dateOfCreation +"'";
										
					//For Generation....
					rs1 = stmt1.executeQuery("select * from generation_details where generation_name = '"+generationName+"'");
					if(rs1.next()){
						message = "Generation name already exists!";
						MessageDialog.openWarning(shell, "Alert", message);
					}else{
						
						rsGene = stmtGene.executeQuery("select max(generation_id) from generation_details");
						while(rsGene.next()){
							if(rsGene.getInt(1) == 0){
								generationId = 1;
							}else{
								generationId = rsGene.getInt(1) + 1;
							}							
						}
//						queryValues = generationId +",'"+ generationName +"','"+ dateOfCreation +"','"+ dateOfCreation +"','completed','"+ null +"',"+ projectId;
						queryValues = generationId +",'"+ generationName +"','"+ dateOfCreation +"','"+ dateOfCreation +"','"+null+"','"+ null +"',"+ projectId;
						
											
						dbOperations.DB_Insert("project_details", values);
						dbOperations.DB_Insert("generation_details", queryValues);
						
						//For Accessions...
						for(int i = 0; i < rootModel.getGenotype().get(0).getAccessions().size(); i++){
							
							String accessionName = rootModel.getGenotype().get(0).getAccessions().get(i).getName();
							rsAcc = stmtAcc.executeQuery("select * from accessions where accession_name = '"+accessionName+"'");
							if(!(rsAcc.next())){
								rsAcc1 = stmtAcc1.executeQuery("select max(accession_id) from accessions");
								while(rsAcc1.next()){
									if(rsAcc1.getInt(1) == 0){
										if(cnt1 == 0){
											accessionId = 1;
											cnt1++;
										}else{
											accessionId = prevAccId + 1;
										}
									}else{
										if(cnt1 == 0){
											accessionId = rsAcc1.getInt(1) + 1;
											cnt1++;
										}else{
											accessionId = prevAccId + 1;
										}
									}
								}
								accValues = accessionId +",'"+ accessionName +"'";								
								//dbOperations.DB_Insert("accessions", accValues);
								pst1.setInt(1, accessionId);
								pst1.setString(2, accessionName);
								prevAccId = accessionId;
								accInfo = "ready";
								
								accList.add(accessionId);
								pst1.addBatch();
							}else{
								accList.add(rsAcc.getInt("accession_id"));
								
							}
							
							
							//System.out.println(rootModel.getGenotype().get(0).getAccessions().get(i).getAllelicValues().get(0).getAllelicValues());
							
							//For Allele values...
							
							for(int l = 0 ; l < rootModel.getGenotype().get(0).getAccessions().get(i).getAllelicValues().get(0).getAllelicValues().size(); l++){
								
								String strAlleleVal = (String) rootModel.getGenotype().get(0).getAccessions().get(i).getAllelicValues().get(0).getAllelicValues().get(l);
								
								if(chkForAllele == 1){
									for(int str = 0; str < strAlleleVal.length(); str++){
										//If we find a non-digit character we will set the value for checkForAllele...
										if (!Character.isDigit(strAlleleVal.charAt(str))){
											FlagAlleleType = "ABH Data";
										}
									}
									chkForAllele ++;
								}
								
								if(FlagAlleleType == ""){
									intAlleleVal = Integer.parseInt(strAlleleVal);	
									rsAllele = stmtAllele.executeQuery("select max(allelevalue_id) from allele_integervalues");
									
								}else{									
									rsAllele = stmtAllele.executeQuery("select max(allelevalue_id) from allele_charvalues");
									
								}
								
								while(rsAllele.next()){
									maxAlleleId = rsAllele.getInt(1);
									if(rsAllele.getInt(1) == 0){
									
										if(cnt == 0){
											alleleId = 1;
											cnt++;
										}else{
											//System.out.println("prevAlleleId : INSIDE"+prevAlleleId);
											alleleId = prevAlleleId + 1;
										}
									}else{
										if(cnt == 0){
											alleleId = rsAllele.getInt(1) + 1;
											cnt++;
										}else{
											//System.out.println("prevAlleleId : INSIDE"+prevAlleleId);
											alleleId = prevAlleleId + 1;
										}
									}
									
									
									if(FlagAlleleType == ""){
										alleleValues = alleleId +",'"+ intAlleleVal +"'";
										tablename = "allele_integervalues";
									}else{
										alleleValues = alleleId +",'"+ strAlleleVal +"'";
										tablename = "allele_charvalues";
									}
									
									//dbOperations.DB_Insert(tablename, alleleValues);
									//System.out.println(alleleId+":::"+intAlleleVal);
									pst.setInt(1, alleleId);
									pst.setInt(2, intAlleleVal);
									prevAlleleId = alleleId;
									//System.out.println(alleleId+":::"+intAlleleVal);
								}
								pst.addBatch();								
							}
							
							/*//For SelectedAccessions...
							for(int sel = 0; sel < rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().size(); sel++){
								//System.out.println(rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().get(sel).getSelAccession());
								System.out.println("select accession_id from accessions where accession_name = '"+rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().get(sel).getSelAccession()+"'");
								rsSelacc = stmtSelacc.executeQuery("select accession_id from accessions where accession_name = '"+rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().get(sel).getSelAccession()+"'");
								//System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
								while(rsSelacc.next()){
									System.out.println("GGGGGGGGGGGGGGGGGGGGGGG");
									rsType = stmtType.executeQuery("select type_id from type_details where type_name = '"+rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().get(sel).getType()+"'");
									while(rsType.next()){
										System.out.println(generationId+":::"+rsSelacc.getInt("accession_id")+":::"+rsType.getInt("type_id"));
										pstSelAcc.setInt(1, generationId);
										pstSelAcc.setInt(2, rsSelacc.getInt("accession_id"));
										pstSelAcc.setInt(3, rsType.getInt("type_id"));
										
									}
									pstSelAcc.addBatch();
								}
							}*/
							
						}
						if(accInfo.equals("ready")){
							pst1.executeBatch();
						}
						pst.executeBatch();
						
						
						cnt = 0;
						cnt1 = 0;
						
						//For SelectedAccessions...
						for(int i = 0; i < rootModel.getGenotype().get(0).getAccessions().size(); i++){							
							for(int sel = 0; sel < rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().size(); sel++){
								rsSelacc = stmtSelacc.executeQuery("select accession_id from accessions where accession_name = '"+rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().get(sel).getSelAccession()+"'");
								while(rsSelacc.next()){
									rsType = stmtType.executeQuery("select type_id from type_details where type_name = '"+rootModel.getGenotype().get(0).getAccessions().get(i).getSelectedAccessions().get(sel).getType()+"'");
									while(rsType.next()){
										pstSelAcc.setInt(1, generationId);
										pstSelAcc.setInt(2, rsSelacc.getInt("accession_id"));
										pstSelAcc.setInt(3, rsType.getInt("type_id"));
										
									}
									pstSelAcc.addBatch();
								}
							}
						}
						pstSelAcc.executeBatch();
						
						//For Markers....
						markerHMapFrmModel = rootModel.getGenotype().get(0).getAccessions().get(0).getMarkersCount();
						
						for(int j = 0; j < rootModel.getGenotype().get(0).getAccessions().get(0).getGmark().size(); j++){
							markerName = rootModel.getGenotype().get(0).getAccessions().get(0).getGmark().get(j);
							rsMar = stmtMar.executeQuery("select * from markers where marker_name = '"+markerName+"'");
							if((!(markerName.equals(prevMarkerName)))){
								if((!(rsMar.next()))){
									//System.out.println("******************************   "+markerName);
									rsMar1 = stmtMar1.executeQuery("select max(marker_id) from markers");
									while(rsMar1.next()){
										if(rsMar1.getInt(1) == 0){
											if(cnt2 == 0){
												markerId = 1;
												cnt2++;
											}else{
												markerId = prevMarkerId + 1;
											}
										}else{
											if(cnt2 == 0){
												markerId = rsMar1.getInt(1) + 1;
												cnt2++;
											}else{
												markerId = prevMarkerId + 1;
											}
										}
									}
									
									markerValues = markerId +",'"+ markerName +"'";
									//dbOperations.DB_Insert("markers", markerValues);
									pst2.setInt(1, markerId);
									pst2.setString(2, markerName);
									prevMarkerId = markerId;
									prevMarkerName = markerName;
									markerInfo = "ready";
									
									markerList.add(markerId);
									markerHMap.put(markerId, markerName);
									pst2.addBatch();
								}else{
									
									//System.out.println(rsMar.getInt("marker_id"));
									markerList.add(rsMar.getInt("marker_id"));
									markerHMap.put(rsMar.getInt("marker_id"), rsMar.getString("marker_name"));
									prevMarkerName = rsMar.getString("marker_name");
								}								
							}
							
						}
						if(markerInfo.equals("ready")){
							pst2.executeBatch();
							cnt2 = 0;
						}
						
						//System.out.println(generationId);
						//System.out.println(accList);
						///System.out.println(markerList);
						//System.out.println(maxAlleleId);
						//System.out.println(markerHMap);
						//System.out.println(markerHMapFrmModel);
						
						//For Reference Table....
						prevAlleleIdCal = maxAlleleId;	
						
						for(int acc = 0; acc < accList.size(); acc++){
							for(int mk = 1; mk <= markerList.size(); mk++){
								if(markerHMapFrmModel.get(markerHMap.get(markerList.get(mk-1))) != null){
									ploidy = markerHMapFrmModel.get(markerHMap.get(markerList.get(1)));
									for(int mkloop = 0; mkloop < markerHMapFrmModel.get(markerHMap.get(markerList.get(mk-1))); mkloop++){
										alleleIdCal = prevAlleleIdCal + 1;
										prevAlleleIdCal = alleleIdCal;
//										System.out.println("acc No. :"+acc+": accession :"+accList.get(acc)+": mk :"+mk+": marker :"+markerList.get(mk-1));
//										System.out.println("generationId :"+generationId+": alleleIdCal :"+alleleIdCal+": marker_id :"+mk+": accession :"+acc);
										
										//System.out.println(":***************** mk :"+mk+": marker :"+markerList.get(mk-1));
										
										pst3.setInt(1, generationId);
										pst3.setInt(2, alleleIdCal);
										pst3.setInt(3, markerList.get(mk-1));
										pst3.setInt(4, accList.get(acc));
										pst3.addBatch();
									}
								}
							}
							
						}
						pst3.executeBatch();
						
						//For QTL....
						for(int qtl = 0; qtl < rootModel.getQtl().get(0).getQtlData().size(); qtl++){
							pstQTL.setInt(1, generationId);
							pstQTL.setString(2, rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlNames());
							pstQTL.setString(3, rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlChromNames());
							pstQTL.setInt(4, Integer.parseInt(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlPeakPoints().get(0).getQtlPeakPoints()));
							pstQTL.setInt(5, Integer.parseInt(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlStartPt()));
							pstQTL.setInt(6, Integer.parseInt(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlEndPt()));
							pstQTL.setString(7, rootModel.getQtl().get(0).getQtlData().get(qtl).getQtltraitName());
							pstQTL.setInt(8, Integer.parseInt(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlEnviName()));
							pstQTL.setFloat(9 , Float.parseFloat(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlLodsqr()));
							pstQTL.setFloat(10, Float.parseFloat(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlRsqr()));
							pstQTL.setFloat(11, Float.parseFloat(rootModel.getQtl().get(0).getQtlData().get(qtl).getQtlAddEffects()));
							
							pstQTL.addBatch();
						}
						
						pstQTL.executeBatch();
						
						//For Markers....
						for(int mk = 0; mk < rootModel.getLinkagemap().get(0).getChromosomes().size(); mk++){
							//System.out.println(rootModel.getLinkagemap().get(0).getChromosomes().get(qtl).getChromosome()+"::"+rootModel.getLinkagemap().get(0).getChromosomes().get(qtl).getMap_marker()+"::"+rootModel.getLinkagemap().get(0).getChromosomes().get(qtl).getNumbering()+"::"+rootModel.getLinkagemap().get(0).getChromosomes().get(qtl).getDistance()+"::"+rootModel.getLinkagemap().get(0).getChromosomes().get(qtl).getMarkerposition());
							//System.out.println(rootModel.getLinkagemap().get(0).getChromosomes().get(qtl).getMap_marker());
							pstMk.setInt(1, generationId);
							pstMk.setString(2, rootModel.getLinkagemap().get(0).getChromosomes().get(mk).getChromosome());
							pstMk.setString(3, rootModel.getLinkagemap().get(0).getChromosomes().get(mk).getMap_marker());
							pstMk.setInt(4, Integer.parseInt(rootModel.getLinkagemap().get(0).getChromosomes().get(mk).getNumbering()));
							pstMk.setFloat(5, Float.parseFloat(rootModel.getLinkagemap().get(0).getChromosomes().get(mk).getDistance()));
							pstMk.setFloat(6, Float.parseFloat(rootModel.getLinkagemap().get(0).getChromosomes().get(mk).getMarkerposition()));
							
							pstMk.addBatch();
						}
						pstMk.executeBatch();
						
						//For Target Genotype.........
						
						for(int tar = 0; tar < TargetGeno.getTargetGeno().getParents().size(); tar++){
							System.out.println("ACCESSION :"+TargetGeno.getTargetGeno().getParents().get(tar).getParent()+"::::"+TargetGeno.getTargetGeno().getParents().get(tar).getType());
							String strTargetAcc = TargetGeno.getTargetGeno().getParents().get(tar).getParent();
							String strTargetAcc1 = "";
							
							
							if(strTargetAcc.contains("Target")){
								strTargetAcc1 = strTargetAcc.substring(0, strTargetAcc.indexOf("Target"));
								
							}else{
								strTargetAcc1 = strTargetAcc;
							}
//							System.out.println("select accession_id from accessions where accession_name = '"+strTargetAcc1+"'");
							rsTargetAcc = stmtTargetAcc.executeQuery("select accession_id from accessions where accession_name = '"+strTargetAcc1+"'");
							while(rsTargetAcc.next()){
								targetAccId = rsTargetAcc.getInt("accession_id");								
							}
							
							if(TargetGeno.getTargetGeno().getParents().get(tar).getType().equals("Donor")){
								donorAccId = targetAccId;
							}
							
							rsTargetType = stmtTargetType.executeQuery("select type_id from type_details where type_name='"+TargetGeno.getTargetGeno().getParents().get(tar).getType()+"'");
							while(rsTargetType.next()){
								targetTypeId = rsTargetType.getInt("type_id");								
							}
							
							
														
							for(int tar1 = 0; tar1 < TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().size(); tar1++){
								String strTargetAllele = TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getTargetAlleleValue();
								//System.out.println("*****************************************************  :::::::::::::::"+strTargetAllele);
								String[] arrTragetAllele = strTargetAllele.split(" ");
								List<Integer> allelefrmDb = new ArrayList<Integer>();
								
								//System.out.println("MARKER NAME *********:::"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getMarkerName());
								//System.out.println("select marker_id from markers where marker_name = '"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getMarkerName()+"'");
								
								rsTargetMarker = stmtTargetMarker.executeQuery("select marker_id from markers where marker_name = '"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getMarkerName()+"'");
								while(rsTargetMarker.next()){
									targetMarkerId = rsTargetMarker.getInt("marker_id");									
								}
								
								//System.out.println("DRAGGED :"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getTargetDraggedValue());
								
								//System.out.println(targetMarkerId+"::::::"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getMarkerName());
								//System.out.println("ORGINIAL"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getTargetAlleleValue());
								//System.out.println("FIRST SPILT :"+arrTragetAllele[0]);
								//System.out.println("SECOND SPILT :"+arrTragetAllele[1]);
								
								//System.out.println("SELECT aint.allele_value from reference rf inner join allele_integervalues aint on rf.allelevalue_id = aint.allelevalue_id where rf.accession_id='"+targetAccId+"' and rf.marker_id='"+targetMarkerId+"' and generation_id='"+generationId+"'");
								rsTargetAlleleFrmDb = stmtTargetAlleleFrmDb.executeQuery("SELECT aint.allele_value from reference rf inner join allele_integervalues aint on rf.allelevalue_id = aint.allelevalue_id where rf.accession_id='"+targetAccId+"' and rf.marker_id='"+targetMarkerId+"' and generation_id='"+generationId+"'");
								while(rsTargetAlleleFrmDb.next()){
									allelefrmDb.add(rsTargetAlleleFrmDb.getInt("allele_value"));									
								}
								
								HashSet<Integer> targetAlleleSet = new HashSet<Integer>();
								List<Integer> test = new ArrayList<Integer>();
								//System.out.println(arrTragetAllele[0]+"::::::OUTSIDE::::::::"+arrTragetAllele[1]);
								//System.out.println("allelefrmDb :"+allelefrmDb);
								
								for(int ta = 0; ta < arrTragetAllele.length; ta++){
									
//									System.out.println("INSIDE LOOP :"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getTargetDraggedValue().get(strTargetAllele));
									//System.out.println(arrTragetAllele[ta]+"::::INSIDE::::"+allelefrmDb.get(ta));
									//System.out.println("WHether it is dragged or not !!!!!"+TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getTargetDraggedValue().get(strTargetAllele));
									if((Integer.parseInt(arrTragetAllele[ta]) == allelefrmDb.get(ta)) && (TargetGeno.getTargetGeno().getParents().get(tar).getSelParents().get(0).getMParents().get(0).getColorAllele().get(tar1).getTargetDraggedValue().get(strTargetAllele)== null)){
										//System.out.println("ONE  1 ****** :"+"SELECT aint.allelevalue_id, aint.allele_value from reference rf inner join allele_integervalues aint on rf.allelevalue_id = aint.allelevalue_id where rf.accession_id='"+targetAccId+"' and rf.marker_id='"+targetMarkerId+"' and generation_id='"+generationId+"' and aint.allele_value='"+arrTragetAllele[ta]+"'");
										rsTargetAllele = stmtTargetAllele.executeQuery("SELECT aint.allelevalue_id, aint.allele_value from reference rf inner join allele_integervalues aint on rf.allelevalue_id = aint.allelevalue_id where rf.accession_id='"+targetAccId+"' and rf.marker_id='"+targetMarkerId+"' and generation_id='"+generationId+"' and aint.allele_value='"+arrTragetAllele[ta]+"'");
										while(rsTargetAllele.next()){
											targetAlleleSet.add(rsTargetAllele.getInt("allelevalue_id"));
										}
									}else{
										//System.out.println("TWO  2 ***** :"+"SELECT aint.allelevalue_id, aint.allele_value from reference rf inner join allele_integervalues aint on rf.allelevalue_id = aint.allelevalue_id where rf.accession_id='"+donorAccId+"' and rf.marker_id='"+targetMarkerId+"' and generation_id='"+generationId+"' and aint.allele_value='"+arrTragetAllele[ta]+"'");
										
										rsTargetAllele = stmtTargetAllele.executeQuery("SELECT aint.allelevalue_id, aint.allele_value from reference rf inner join allele_integervalues aint on rf.allelevalue_id = aint.allelevalue_id where rf.accession_id='"+donorAccId+"' and rf.marker_id='"+targetMarkerId+"' and generation_id='"+generationId+"' and aint.allele_value='"+arrTragetAllele[ta]+"'");
										while(rsTargetAllele.next()){
											targetAlleleSet.add(rsTargetAllele.getInt("allelevalue_id"));
										}
									}
								}
								
//								System.out.println("targetAlleleSet*******:::"+targetAlleleSet);
								for(Iterator<Integer> it = targetAlleleSet.iterator(); it.hasNext();){
									test.add(it.next());	
								}
								for(int arr =0;arr<test.size();arr++){
									//System.out.println("test*******:::"+test.get(arr));
									pstTargetallele.setInt(1, generationId);
									pstTargetallele.setInt(2, targetAccId);
									pstTargetallele.setInt(3, targetMarkerId);
									pstTargetallele.setInt(4, test.get(arr));
									pstTargetallele.setInt(5, targetTypeId);
									pstTargetallele.setInt(6, 0);
									pstTargetallele.setString(7, null);
									
									targetInfo = "ready";
									pstTargetallele.addBatch();
									
								}	
							}
						}
						if(targetInfo == "ready"){
							int val[] = pstTargetallele.executeBatch();
							if(val.length > 0){
								saveType = "completed";								
							}
						}
						
						if(saveType.equals("completed")){
							saveTypeToDB = "completed";
						}else{
							saveTypeToDB = "Not completed";
						}
						stmtSaveType.executeUpdate("Update generation_details set status = '"+saveTypeToDB+"', ploidy = '"+ploidy+"' where generation_id='"+generationId+"'");						
						
					}					
				}
				

					
						
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}catch(Exception e){
				e.printStackTrace();			
			}finally{
				try{
					if(con!=null){
						con.close();					
					}
				}catch(Exception e){
					e.printStackTrace();
					System.out.println(e);
				}
			}
		
					try {
						IProject project = null;
						if(ResourcesPlugin.getWorkspace().getRoot().getProjects().length > 0){
							
							project = ResourcesPlugin.getWorkspace().getRoot().getProjects()[0];
							
						}else{
						
							project = ResourcesPlugin.getWorkspace().getRoot().getProject("Sample Project");
							
							//creating the Project named Sample Project......
							//NullProgressMonitor() is a Null class provided by the ECLIPSE instead of passing NULL...
							project.create(new NullProgressMonitor());
						}
						/*	Whenever we create a New Project It is in the CLOSED STATE...
						 * 	So we need to manually OPEN the Project
						 *  
						 */
						if(!project.isOpen()){
							
							project.open(new NullProgressMonitor());									
						}
						
						IFile file = project.getFile("Ismab.mygef");
						if(file.exists()){
							//if FIle already exists then it deletes and creates the new File...
							file.delete(true, new NullProgressMonitor());									
						}
						//file.create(new FileInputStream(filepath), true, new NullProgressMonitor());
							
					//	IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file);;
					
						
						
					}catch (CoreException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			//making to run the thread asynchronously...
			Display.getDefault().asyncExec(run);
			
			//telling that second job is completed...
			monitor.worked(1);
			
			//telling that job is completed...
			monitor.done();
			
			return Status.OK_STATUS;
		}
	};
	wJob.setUser(true);
	//it runs the schedule job
	wJob.schedule();
		}		
		
	}	
	
	
	
	public void dispose() {
		// TODO Auto-generated method stub

	}

}


